import {
  getInterfaceInfoByIdUsingGet,
  invokeInterfaceInfoUsingPost
} from '@/services/api-backend/interfaceInfoController';
import { PageContainer } from '@ant-design/pro-components';
import { useParams } from '@umijs/max';
import {  Button, Card, Descriptions, Form, Input, message } from 'antd';
import React, { useEffect, useState } from 'react';

const index: React.FC = () => {

  const [loading,setLoading] = useState(false);
  const [data,setData]=useState<API.InterfaceInfo>();
  const params=useParams();
  const [invokeRes,setInvokeRes] = useState<any>();
  const [InvokeLoading,setInvokeLoading] = useState(false);

  const loadData=async ()=>{
    setLoading(true);
    try{
      const res =await getInterfaceInfoByIdUsingGet({
        id:Number(params.id)
      });
      setData(res.data);
    }catch(error:any){
      message.error('请求失败，'+error.message);
    }
    setLoading(false);
  }

  useEffect(()=>{
    loadData();
  },[])

  const onFinish = async (values: any) => {
    setInvokeLoading(true);
    if(!params.id){
      message.error('接口不存在');
      return;
    }

    try{
      const res=await invokeInterfaceInfoUsingPost({
        id:Number( params.id),
        ...values,
      });
      console.log('res为'+res.data)
      setInvokeRes(res.data);

      message.success('请求成功')
    }catch(error:any){
      message.error('请求失败，'+error.message);
    }
    setInvokeLoading(false);
  }

  return (
    <PageContainer title="查看接口文档">
      <Card>
        {data?(
          <Descriptions title={data.name} column={1} extra={<Button>调用</Button>}>
            <Descriptions.Item label="接口状态">{data.status?'开启':'关闭'}</Descriptions.Item>
            <Descriptions.Item label="描述">{data.descpition}</Descriptions.Item>
            <Descriptions.Item label="请求地址">{data.url}</Descriptions.Item>
            <Descriptions.Item label="请求方法">{data.method}</Descriptions.Item>
            <Descriptions.Item label="请求参数">{data.requestParams}</Descriptions.Item>
            <Descriptions.Item label="请求头">{data.requestHeader}</Descriptions.Item>
            <Descriptions.Item label="响应头">{data.responseHeader}</Descriptions.Item>
            <Descriptions.Item label="创建时间">{data.createTime}</Descriptions.Item>
            <Descriptions.Item label="更新时间">{data.updateTime}</Descriptions.Item>
          </Descriptions>
        ):(
          <></>
        )
        }
      </Card>
      <Card title='在线调用'>
        <Form
          name='invoke'
          onFinish={onFinish}>
          <Form.Item
            label="请求参数"
            name="userRequestParams"
          >
            <Input.TextArea/>
          </Form.Item>
          <Form.Item wrapperCol={{offset:9,span:16}}>
            <Button type='primary' htmlType='submit'>
              调用
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <Card title='返回结果' loading={InvokeLoading} >
        {invokeRes}
      </Card>
    </PageContainer>
  );
}




export default index;
